package swu.cx.myhttpjava;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class ThreadPoolManager {
    private LinkedBlockingQueue<Runnable> mQueue = new LinkedBlockingQueue<>();
    private ThreadPoolExecutor mThreadPoolExecutor;
    public Runnable coreThread = new Runnable() {
        Runnable runn = null;
        @Override
        public void run() {
            while (true){
                try {
                    runn = mQueue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mThreadPoolExecutor.execute(runn);
            }
        }
    };
    private ThreadPoolManager(){
        mThreadPoolExecutor = new ThreadPoolExecutor(3, 10, 15, TimeUnit.SECONDS, new ArrayBlockingQueue< Runnable >(5)
                , new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
                addTask(runnable);
            }
        });
        mThreadPoolExecutor.execute(coreThread);
    }
    private static  ThreadPoolManager instance = new ThreadPoolManager();
    public static ThreadPoolManager getInstance(){
        return instance;
    }
    public void addTask(Runnable runnable){
        try {
            mQueue.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
